import { Button, Card, message, Popconfirm, Switch, Table, Tag } from 'antd';
import React, { useEffect, useState } from 'react';

import DictionarySubDataService from '@/api/services/stars/dictionarySubDataService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import SubDataModal from '@/pages/setting/dictionary/sub-data/sub-data-modal';
import ProTag from '@/theme/antd/components/tag';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';

import { SubDictionariesData } from './type';

import { ListData, ModalProps, PageForm } from '#/entity';
import type { ColumnsType } from 'antd/es/table';

interface SubDictionaryDataProps {
  parentId?: string;
}

const defaultSubDictionaryValue: SubDictionariesData = {
  typeId: '',
  value: '',
  key: '',
  sort: 0,
};

function SubDictionaryData({ parentId }: SubDictionaryDataProps) {
  // 状态管理
  const [dataSource, setDataSource] = useState<ListData<SubDictionariesData>>();
  const [searchForm, setSearchForm] = useState<PageForm>({
    page: 1,
    take: 10,
  });

  const handleDelete = (id: string) => {
    DictionarySubDataService.remove({ ids: [id] }).then((res) => {
      if (res > 0) {
        message
          .open({
            content: '删除成功',
            type: 'error',
            duration: 1,
          })
          .then();
        fetchData();
      }
    });
  };
  const [modalProps, setModalProps] = useState<ModalProps<SubDictionariesData>>({
    show: false,
    title: '',
    formValue: defaultSubDictionaryValue,
    onOk: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
      fetchData();
    },
    onCancel: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const onEdit = (row: SubDictionariesData) => {
    row.typeId = parentId!;
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改',
      formValue: row,
    }));
  };
  // 获取信息
  useEffect(() => {
    DictionarySubDataService.list(parentId, searchForm).then((res) => {
      setDataSource(res);
    });
  }, [parentId, searchForm]);
  const fetchData = () => {
    DictionarySubDataService.list(parentId, searchForm).then((res) => {
      setDataSource(res);
    });
  };
  const onCreate = () => {
    defaultSubDictionaryValue.typeId = parentId!;
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '新增',
      formValue: defaultSubDictionaryValue,
    }));
  };
  // 表格列配置
  const columns: ColumnsType<SubDictionariesData> = [
    {
      title: '字典键',
      dataIndex: 'key',
      align: 'center',
      width: 100,
      render: (type) => {
        return <ProTag color="orange">{type}</ProTag>;
      },
    },
    {
      title: '字典值',
      dataIndex: 'value',
      width: 100,
      align: 'center',
    },
    {
      title: '字典排序',
      dataIndex: 'sort',
      width: 100,
      align: 'center',
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      width: 100,
      align: 'center',
      render: (status, dictionariesData: SubDictionariesData) => {
        return (
          <Switch
            checked={status}
            onChange={(status: boolean) => {
              const updateForm = {
                status,
                typeId: dictionariesData.typeId,
                key: dictionariesData.key,
                system: dictionariesData.system,
              };

              DictionarySubDataService.edit(dictionariesData.id, updateForm).then((res) => {
                setSearchForm({
                  page:
                    dataSource?.data.length === 1 && searchForm.page > 1
                      ? searchForm.page - 1
                      : searchForm.page,
                  take: searchForm.take,
                });
              });
            }}
          />
        );
      },
    },
    {
      title: '字典说明',
      dataIndex: 'remark',
      align: 'center',
      width: 180,
      render: (type) => {
        return <Tag color="pink">{type}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      align: 'center',
      width: 200,
      render: (createAt: string) => {
        return datetime(createAt);
      },
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'createBy',
      width: 100,
      render: (createBy) => {
        return createBy.name;
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      render: (record: SubDictionariesData) => (
        <div className="flex justify-center gap-2">
          {hasPermission('STARS:DICTIONARIES_DATA:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="修改">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('STARS:DICTIONARIES_DATA:DELETE') && (
            <Popconfirm
              title="确认删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => handleDelete(record.id)}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  return (
    <Card
      title={
        <div className="flex items-center gap-2">
          <Button
            type="primary"
            disabled={!hasPermission('STARS:DICTIONARIES_DATA:CREATE')}
            onClick={() => {
              onCreate();
            }}
          >
            新增
          </Button>
        </div>
      }
    >
      <Table
        size="small"
        rowKey="id"
        scroll={{ x: 'max-content' }}
        columns={columns}
        dataSource={dataSource?.data}
        pagination={{
          current: searchForm.page,
          pageSize: searchForm.take,
          total: dataSource?.count, // 新增：总条目数
          // showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, size) => {
            setSearchForm((prev) => ({ ...prev, page, take: size }));
          },
        }}
      />
      <SubDataModal {...modalProps} />
    </Card>
  );
}

export default SubDictionaryData;
